﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using WPFCanvas.CustomControls;

namespace ExORMDesginer.Helper
{
    public class ElementHelper
    {

        public static INodeView GetElementByINodeView(DependencyObject parent)
        {
            INodeView grandChild;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(parent) - 1; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is INodeView)
                    return (INodeView)child;
                else
                {
                    grandChild = GetElementByINodeView(child);
                    if (grandChild != null)
                        return grandChild;
                }



            }
            return null;
          
        }


        public static T FindElementByType<T>(DependencyObject parent) where T : FrameworkElement
        {

            T grandChild = null;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(parent) - 1; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is T)
                    return (T)child;
                else
                {
                    grandChild= FindElementByType<T>(child);
                    if (grandChild != null)
                        return grandChild;
                }


              
            }


            return null;
        }


        public static T FindParentElementByType<T>(FrameworkElement obj) where T:FrameworkElement
        {
            FrameworkElement parent = obj;
            while (!(parent is T))
            {
                parent = parent.Parent as FrameworkElement;
                if (parent == null)
                    break;
            }
            return (T)parent;
        }



        public static List<T> FindElementByTypes<T>(DependencyObject parent) where T : FrameworkElement
        {
            List<T> childs = new List<T>();
            T grandChild = null;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(parent) - 1; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is T)
                {
                    childs.Add((T)child);
                }

                var ls = FindElementByTypes<T>(child);
                if (ls.Count > 0)
                    childs.AddRange(ls);

            }


            return childs;
        }

    }
}
